import env from "../../../utils/env"
Page({
  /**
   * 页面的初始数据
   */
  data: {
    corpRole: wx.getStorageSync('userInfo').corpRole,
    grade: '', //判断走访统计总览/银行详情
    pageNum: 0,
    name: '',
    // 搜索
    serach_pro: "",
    prosum: null,
    prolist: [],
    showSelect: false,
    bankId: '',
    oriProlist: [],
    loading: true,
    userInfo: null,
    totalPages: 1,
    multiple: 10,
    flag: '',
    pickerList: [{
        id: '0',
        name: '全部'
      },
      {
        id: '1',
        name: '2023年03月-第一批次'
      },
      {
        id: '2',
        name: '2023年05月-第二批次'
      },
      {
        id: '3',
        name: '2023年06月-第三批次'
      },
      {
        id: '4',
        name: '2023年07月-第四批次'
      },
      {
        id: '5',
        name: '2023年08月-第五批次'
      },
      {
        id: '6',
        name: '2023年08月-第六批次'
      },  {
        id: '7',
        name: '2023年10月-第七批次'
      }, {
        id: '8',
        name: '2023年12月-第八批次'
      },{
        id: '9',
        name: '2024年01月-第九批次'
      },{
        id: '10',
        name: '2024年02月-第十批次'
      },{
        id: '11',
        name: '2024年03月-第十一批次'
      },
      {
        id: '12',
        name: '2024年03月-第十二批次'
      },
    ],
    selectPc: '全部',
  },
  checkDetail(e) {
    console.log(e.currentTarget.dataset.id)
    wx.navigateTo({
      url: `/pages/visitList/visitList?permission=1&userId=${e.currentTarget.dataset.id}`,
    });
  },
  goOnChange(e) {
    this.setData({
      serach_pro: e.detail,
    });
  },
  openMethod() {
    this.setData({
      showSelect: true,
    });
  },
  hideSelect() {
    this.setData({
      showSelect: false,
    });
  },
  goCopy() {
    let that = this;
    wx.setClipboardData({
      data: "www.baidu.com",
      success(res) {
        that.hideSelect();
        wx.showToast({
          title: "链接已复制",
          icon: "none",
        });
      },
    });
  },
  // 搜索
  serachProChange(e) {
    this.setData({
      prolist: [{
        bankId: "",
        bankName: "全部分支行",
      }, ],
      serach_pro: e.detail,
    });
  },

  goExport() {

  },

  onChange(e) {
    console.log(e, 'ee')
    const id = this.data.pickerList[Number(e.detail.value)].id
    this.setData({
      pageNum:1,
      selectPcId: id,
      selectPc: this.data.pickerList[Number(e.detail.value)].name
    })
    // 重新查询
    this.getList()
  },

  // 搜索
  goSearch() {
    this.setData({
      totalPages: 1,
      pageNum: 0,
    })
    this.getList()
  },
  // 滑动底部加载更多
  scrollBottom() {
    // this.onBottom();
  },
  downPage() {
    this.data.pageNum++
    this.setData({
      pageNum: this.data.pageNum
    })
    this.data.prolist = this.data.oriProlist.slice(this.data.multiple * this.data.pageNum, this.data.multiple * this.data.pageNum + this.data.multiple)
    this.setData({
      prolist: this.data.prolist
    })
    this.goTop()
    // console.log(this.data.prolist, 'this.data.prolist')
  },
  upPage() {
    this.data.pageNum--
    this.setData({
      pageNum: this.data.pageNum
    })
    this.data.prolist = this.data.oriProlist.slice(this.data.multiple * this.data.pageNum, this.data.multiple * this.data.pageNum + this.data.multiple)
    this.setData({
      prolist: this.data.prolist
    })
    this.goTop()
    console.log(this.data.prolist, '上一页this.data.prolist')
  },
  //回到顶部
  goTop: function (e) { // 一键回到顶部
    if (wx.pageScrollTo) {
      wx.pageScrollTo({
        scrollTop: 0
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法回到顶部，请升级到最新微信版本后重试。'
      })
    }
  },
  // 新版本
  getList() {
    var _this = this;
    this.setData({
      loading: true,
    });
    wx.showLoading({
      title: "加载中",
    });
    console.log(this.data.grade, 'bankIdbankId')
    const params = {
      bankId: this.data.bankId,
      grade: this.data.grade,
      batchNum: this.data.selectPcId === '0' ? '' : this.data.selectPcId
    };
    console.log(params, '志文')
    // if (this.data.flag) {
    //   params.flag = '1'
    // }
    getApp()
      .globalData.request("/corpVisit/detail", params, "POST")
      .then((res) => {
        setTimeout(function () {
          wx.hideLoading();
        }, 500);
        var rstObj = res;
        if (rstObj.data) {
          for (let i in rstObj.data) {

            if (rstObj.data[i].name == null) {
              rstObj.data[i].name = ' '
            }
          }
          console.log(rstObj.data, "res33333");
          let prolist = rstObj.data.filter(
            d =>
            d.name &&
            (d.name.indexOf(this.data.serach_pro.toLowerCase()) !== -1 ||
              d.name.indexOf(this.data.serach_pro.toUpperCase()) !== -1)
          );
          this.setData({
            oriProlist: JSON.parse(JSON.stringify(prolist)),
            prolist: JSON.parse(JSON.stringify(prolist)).slice(0, this.data.multiple),
            loading: false,
            totalPages: Math.ceil(prolist.length / this.data.multiple)
          });
        }
      });
  },

  async openMethod() {
    const res = await this.download()
    setTimeout(function () {
      wx.hideLoading();
    }, 200);
    this.setData({
      showSelect: true,
    });
  },
  download() {
    // wx.showLoading({
    //   title: "导出中...",
    // });
    const _this = this
    console.log(_this.data.grade, 'd')
    const params = {
      // bankId: _this.data.bankId,
      bankId: _this.data.bankId,
      flag: _this.data.grade,
      corpType: wx.getStorageSync('corpType'),
      name: '',
      batchNum: this.data.selectPcId === '0' ? '' : this.data.selectPcId
    }
    console.log(params, 'params')
    // if (this.data.flag) {
    //   params.flag = '1'
    // }
    return new Promise(function (resolve, reject) {
      console.log(resolve, 'resolveresolveresolve')
      wx.request({
        // url: 'http://192.168.1.200:20100/visit/managerStatisticsExport ',
        // url: 'https://fintech-wx.szjrgzjg.com/visit/managerStatisticsExport',
        // ==============================
        url: env.baseUrl + '/corpVisit/managerStatisticsExport',
        data: params,
        method: 'POST',
        header: {
          "content-type": "application/json",
          "token": wx.getStorageSync('token')
        },
        responseType: "arraybuffer", //注意这里的responseType
        success: (result) => {
          console.log(result, '接口调用成功')

          let fileManager = wx.getFileSystemManager();

          _this.data.FilePath = wx.env.USER_DATA_PATH + "/" + 'zx' + '-' + '测试.xls';
          fileManager.writeFile({
            data: result.data,
            filePath: _this.data.FilePath,
            encoding: "binary", //编码方式 
            success: res => {

              resolve('1111')

            },
            fail: res => {
              wx.showToast({
                title: '下载失败!',
                icon: 'none', //默认值是success,就算没有icon这个值，就算有其他值最终也显示success
                duration: 2000, //停留时间
              })
            }
          })
        },
        fail(err) {
          console.log(err)
        }
      })
    })

  },
  async downloadWx() {
    const _this = this
    // const res = await _this.download()
    // console.log(res, '下载最后')
    wx.shareFileMessage({
      filePath: _this.data.FilePath,
      fileName: '客户经理走访信息.xls',
      success(data) {
        _this.hideSelect()
      },
      fail(res) {
        console.log(res, '分享报错的原因')
        // wx.showToast({
        //   title: JSON.stringify(res),
        //   icon: "none"
        // })
      }
    })
  },
  onBottom() {
    if (this.data.prolist.length >= this.data.prosum) return;
    this.data.pageNum++;
    this.getList();
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    wx.setNavigationBarTitle({
      title: options.name, //页面标题为路由参数
    });
    console.log(options.grade, 'options.grade')
    this.setData({
      grade: options.grade,
      bankId: options.bankId,
      name: options.name,
      flag: options.flag || ''
    })

    // const list = [{
    //   name: '苏州银行'
    // }, {
    //   name: '中国银行'
    // }]
    // this.setData({
    //   prolist: list,
    //   prosum: 2
    // })
    this.getList();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
});